from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pygtrans import Translate
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time


class figma_translation:

    def __init__(self):
        # 谷歌浏览器的安装路径：/Applications/Google Chrome.app/Contents/MacOS/Google Chrome
        # 设置Chrome浏览器选项
        self.chrome_options = webdriver.ChromeOptions()
        # 这里的端口号可能需要根据实际情况进行修改
        self.chrome_options.debugger_address = "localhost:9222"
        self.a = ChromeDriverManager().install()
        print(f"google_driver自动适配下载保存地址：{self.a}")
        # 自动适配google浏览器的驱动，不需要本地下载和配置环境变量了
        # 启动Chrome浏览器，完成复用，复用的参数写进去了 options=chrome_options
        self.driver = webdriver.Chrome(executable_path=self.a, options=self.chrome_options)
        self.driver.implicitly_wait(10)

    def element(self, value):
        element = WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, value)))
        return element

    def elements(self, value):
        elements = self.driver.find_elements(By.XPATH, value)
        return elements

    def tihuan_data(self, old_data, new_data, list_num=0):
        # 输入需要替换的数据
        b = self.elements('//textarea[@dir="auto"]')[0]
        b.clear()
        b.send_keys(old_data)
        # 输入被替换的数据
        c = self.elements('//textarea[@dir="auto"]')[1]
        c.clear()
        c.send_keys(new_data)

        # 找到所有查找到的数据，选择第二个元素
        d = self.elements('//span[@class="canvas_search--strikethrough--jicY9"]')
        d[list_num].click()
        # 点击替换
        e = self.elements('//span[contains(text(),"Replace")]')[0]
        e.click()

    def google_translate_texts(self, list_old_data, old_language=None, new_language=None):
        if old_language is None:
            old_language = 'zh-CN'
        if new_language is None:
            new_language = 'en'
        client = Translate(source=old_language, fmt='text', target=new_language)
        new_datas = client.translate(list_old_data)
        list_new_data = []
        for i in new_datas:
            list_new_data.append(i.translatedText)
        return list_new_data

    def figma_translation(self, list_old_data, new_languages_list, old_languages=None):
        if old_languages is None:
            old_languages = 'zh-CN'
        # 获取当前窗口并且转移到当前窗口进行操作
        a = self.driver.window_handles  # 获取到所有页面
        c = a[-1]  # 第一个页面的窗口句柄
        # search = self.driver.current_window_handle
        self.driver.switch_to.window(c)  # 永远跳转到第一个页面
        # self.driver.get(figma_url)
        # 按语言循环
        for new_language in new_languages_list:
            # 原始数据翻译指定语言数据
            list_new_data = self.google_translate_texts(list_old_data, old_language=old_languages,
                                                        new_language=new_language)
            # 循环替换数据
            for i, new_data in zip(list_old_data, list_new_data):
                # 将 i 翻译成指定数据，再填写进来
                print(f"{new_language}语翻译：原文：{i}；译文：{new_data}")
                self.tihuan_data(i, new_data)
                time.sleep(0.5)
            # 关闭当前窗口
            # driver.close()
            # 退出驱动并关闭所有相关窗口和进程
            # time.sleep(5)
            # driver.quit()


if __name__ == '__main__':
    # 执行步骤，非常重要
    # 1. 手动在终端执行： open -search_text "Google Chrome" --args --remote-debugging-port=9222
    # 2. 再运行代码
    # ——————————————————————————————————————————————————————————————————————————————————
    # 原始数据
    # 需要翻译的数据
    list_old_data = ["更像我", "不要我"]

    # 源语言
    old_languages = "zh-CN"

    # 目标语言
    new_languages_list = ["fr", "ja", "de", "es", "ko", "pt", "it", "nl", "sv", "pl", "ru", "da", "fi", "no",
                          "id", "vi", "th", "zh-TW"]

    # 查目标语言的网站 https://pygtrans.readthedocs.io/zh-cn/latest/target.html
    figma_translation().figma_translation(list_old_data, new_languages_list, old_languages=old_languages)
    # 测试网站：https://www.figma.com/file/jD5vcM0RMufFweAvAoiQiV/Untitled?type=design&node-id=0-1&mode=design&t=8gmeb61KYlohyEb9-0
